package com.yangtu.nearbyshop.merc.web;

import com.yangtu.nearbyshop.core.system.SystemConfig;
import com.yangtu.nearbyshop.core.util.ResponseUtil;
import com.yangtu.nearbyshop.db.domain.NearbyshopMerc;
import com.yangtu.nearbyshop.db.service.*;
import com.yangtu.nearbyshop.merc.annotation.LoginMerc;
import com.yangtu.nearbyshop.merc.service.MercHomeCacheManager;
import com.yangtu.nearbyshop.merc.service.MercTokenManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 首页服务
 */
@RestController
@RequestMapping("/merc/home")
@Validated
public class MercHomeController {
    private final Log logger = LogFactory.getLog(MercHomeController.class);

    @Autowired
    private NearbyshopMercService mercService;

    @Autowired
    private NearbyshopOrderService orderService;

    public static DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

//    private final static ArrayBlockingQueue<Runnable> WORK_QUEUE = new ArrayBlockingQueue<>(9);

//    private final static RejectedExecutionHandler HANDLER = new ThreadPoolExecutor.CallerRunsPolicy();

//    private static ThreadPoolExecutor executorService = new ThreadPoolExecutor(9, 9, 1000, TimeUnit.MILLISECONDS, WORK_QUEUE, HANDLER);

    @GetMapping("/cache")
    public Object cache(@NotNull String key) {
        if (!key.equals("nearbyshop_cache")) {
            return ResponseUtil.fail();
        }

        // 清除缓存
        MercHomeCacheManager.clearAll();
        return ResponseUtil.ok("缓存已清除");
    }

    /**
     * 首页数据
     * @param mercId 当用户已经登录时，非空。为登录状态为null
     * @return 首页数据
     */
    @GetMapping("/index")
    public Object index(@LoginMerc Integer mercId) {
        //优先从缓存中读取
//        if (MercHomeCacheManager.hasData(MercHomeCacheManager.INDEX)) {
//            return ResponseUtil.ok(MercHomeCacheManager.getCacheData(MercHomeCacheManager.INDEX));
//        }
//        ExecutorService executorService = Executors.newFixedThreadPool(10);

        if (mercId == null) {
            return ResponseUtil.unlogin();
        }

        Map<String, Object> data = new HashMap<>();

        String mercNo =MercTokenManager.getMercNo(mercId);
        if (mercNo == null) {
            return ResponseUtil.unlogin();
        }
        NearbyshopMerc merc = mercService.queryByMercNo(mercNo);

        data.put("orderCount", orderService.count(mercNo));
        data.put("orderTodayCount", orderService.countToday(mercNo));
        data.put("totalAmt", orderService.getProfit(mercNo));
        String today_start = df.format(LocalDateTime.of(LocalDate.now(), LocalTime.MIN));
        String today_end = df.format(LocalDateTime.of(LocalDate.now(), LocalTime.MAX));
        List<NearbyshopMerc> mercList = mercService.queryByReferMercNo(mercNo);
        String selfAmt = orderService.getProfitByDt(mercNo, today_start, today_end);
        data.put("selfAmt", selfAmt);
        if (mercList.size() == 0) {
            data.put("todayAmt", selfAmt);
            data.put("referAmt", "0");
        }else {
            BigDecimal sumAmt = BigDecimal.ZERO;
            String referAmt;
            for (NearbyshopMerc referMerc: mercList) {
                referAmt = orderService.getProfitByDt(referMerc.getMercNo(), today_start, today_end);
                sumAmt = new BigDecimal(referAmt).add(sumAmt);
            }
            BigDecimal referSumAmt = sumAmt.multiply(SystemConfig.getMercReferPercent()).setScale(2, BigDecimal.ROUND_UP).stripTrailingZeros();
            data.put("todayAmt", referSumAmt.add(new BigDecimal(selfAmt)));
            data.put("referAmt", referSumAmt.stripTrailingZeros().toPlainString());
        }
        data.put("mercNm", merc.getMercName());
        data.put("mobile", merc.getMobile());
        data.put("mercNo", merc.getMercNo());

        //缓存数据
//        MercHomeCacheManager.loadData(MercHomeCacheManager.INDEX, data);
//        executorService.shutdown();
        return ResponseUtil.ok(data);
    }

    public static void main(String[] args) {
        System.out.println(df.format(LocalDateTime.of(LocalDate.now(), LocalTime.MIN)));
    }
}